package cn.school.controller.course;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.common.utils.CourseUtils;
import cn.school.common.utils.SysUserUtils;
import cn.school.common.utils.WeekVo;
import cn.school.course.entity.Course;
import cn.school.course.entity.CourseSessions;
import cn.school.course.service.CourseConflictService;
import cn.school.course.service.CourseService;
import cn.school.course.service.CourseSessionsService;
import cn.school.course.vo.WeekCourseTableBySchoolClassReqVo;
import cn.school.course.vo.WeekCourseTableBySchoolClassRspVo;
import cn.school.sys.entity.SysConfig;
import cn.school.sys.entity.TermTime;
import cn.school.sys.service.SysConfigService;
import cn.school.sys.service.TermTimeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 课程管理
 *
 * @className: CourseController
 * @author: fangjin.tao
 * @date: 2023/1/10
 **/
@RestController
@RequestMapping("/course")
@Api(tags = "CourseController => 课程管理")
public class CourseController {
	private static final Logger log = LoggerFactory.getLogger(CourseController.class);
	@Autowired
	private CourseService courseService;
	@Autowired
	private CourseSessionsService courseSessionsService;
	@Autowired
	private CourseConflictService courseConflictService;
	@Autowired
	private SysConfigService sysConfigService;
	@Autowired
	private TermTimeService termTimeService;
	
	@ApiOperation("课程列表")
	@GetMapping("list")
	public CommonResult<CommonPage<Course>> list(@RequestParam Map<String, Object> params) {
		String pageNum = (String) params.get("pageNum");
		String pageSize = (String) params.get("pageSize");
		String subjId = (String) params.get("subjId"); // 科目ID
		String scclId = (String) params.get("scclId"); // 班级ID
		String coseId = (String) params.get("coseId"); // 节次ID
		String syusId = (String) params.get("syusId"); // 教员用户ID
		String bsloId = (String) params.get("bsloId"); // 场所教室ID
		Object cpcoIsConflict = params.get("cpcoIsConflict"); // 冲突类型
		
		String courBeginAreaTime = (String) params.get("courBeginAreaTime"); // 查询课程左区间
		String courEndAreaTime = (String) params.get("courEndAreaTime"); // 查询课程右区间
		
		IPage<Course> page = new Page(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
		if (StrUtil.isNotEmpty(courBeginAreaTime)) {
			queryWrapper.ge("cour.cour_begin_time", DateUtil.beginOfDay(DateUtil.parse(courBeginAreaTime)));
		}
		if (cpcoIsConflict != null) {
			queryWrapper.eq("coco.cpco_is_conflict", "true".equals(cpcoIsConflict.toString()) ? 1 : 0);
		}
		if (StrUtil.isNotEmpty(courEndAreaTime)) {
			queryWrapper.le("cour.cour_end_time", DateUtil.beginOfDay(DateUtil.parse(courEndAreaTime)));
		}
		if (StrUtil.isNotEmpty(subjId)) {
			queryWrapper.eq("cour.subj_id", Long.parseLong(subjId));
		}
		if (StrUtil.isNotEmpty(scclId)) {
			queryWrapper.eq("cour.sccl_id", Long.parseLong(scclId));
		}
		if (StrUtil.isNotEmpty(coseId)) {
			queryWrapper.eq("cour.cose_id", Long.parseLong(coseId));
		}
		if (StrUtil.isNotEmpty(syusId)) {
			queryWrapper.eq("cour.syus_id", Long.parseLong(syusId));
		}
		if (StrUtil.isNotEmpty(bsloId)) {
			queryWrapper.eq("cour.bslo_id", Long.parseLong(bsloId));
		}
		//租户
		queryWrapper.eq("cour.tenant_id", SysUserUtils.getSysUser().getTenantId());

		queryWrapper.orderByDesc("cour.cour_begin_time");
		
		page = courseService.pageByCourseList(page, queryWrapper);
		return CommonResult.success(CommonPage.restPage(page));
	}
	
	
	@ApiOperation("课程周课表")
	@GetMapping("classCourseTable")
	public CommonResult<WeekCourseTableBySchoolClassRspVo> classCourseTable(@RequestParam Map<String, Object> params) {
		// 获取条件
//		String pageSize = (String) params.get("pageSize");
		String scclId = (String) params.get("scclId"); // 班级ID
		String syusId = (String) params.get("syusId"); // 教员用户ID
		String subjId = (String) params.get("subjId"); // 科目ID
		String tetiId = (String) params.get("tetiId"); // 学年学期
//		String coseId = (String) params.get("coseId"); // 节次ID
		String copsId = (String) params.get("copsId"); // 排课计划ID
//		String bsloId = (String) params.get("bsloId"); // 场所教室ID
		String courBeginAreaTime = (String) params.get("courBeginAreaTime"); // 查询课程左区间
		String courEndAreaTime = (String) params.get("courEndAreaTime"); // 查询课程右区间
		// 获取设置的学年学期
		LambdaQueryWrapper<SysConfig> sysConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
		sysConfigLambdaQueryWrapper.eq(SysConfig::getParamKey, "current_genner_term_time");
		List<SysConfig> sysList = sysConfigService.list(sysConfigLambdaQueryWrapper);
		TermTime termTime = null;
		if (StrUtil.isNotEmpty(tetiId)) {
			termTime = this.termTimeService.getTermTimeById(Long.parseLong(tetiId));
		}
		
		if (termTime == null && sysList != null && sysList.size() != 0) {
			if (StrUtil.isNotEmpty(sysList.get(0).getParamValue())) {
				termTime = this.termTimeService.getTermTimeById(Long.parseLong(sysList.get(0).getParamValue()));
			}
		}
		/*if (termTime == null) {
			log.info("系统配置：生成课程的学年学期（current_genner_term_time）没有配置值\n");
			throw new ApiException("系统配置：生成课程的学年学期（current_genner_term_time）没有配置值");
		} else {
			if (!((DateUtil.beginOfDay(termTime.getTetiTermBeginDate()).getTime() <= DateUtil.beginOfDay(DateUtil.parse(courBeginAreaTime)).getTime()
					&& DateUtil.beginOfDay(DateUtil.parse(courBeginAreaTime)).getTime() <= DateUtil.endOfDay(termTime.getTetiTermEndDate()).getTime())
					|| (DateUtil.beginOfDay(termTime.getTetiTermBeginDate()).getTime() <= DateUtil.endOfDay(DateUtil.parse(courEndAreaTime)).getTime()
					&& DateUtil.endOfDay(DateUtil.parse(courEndAreaTime)).getTime() <= DateUtil.endOfDay(termTime.getTetiTermEndDate()).getTime()))) {
				 throw new ApiException("日期区间不在，系统配置的学年学期的日期内【" + DateUtil.format(termTime.getTetiTermBeginDate(),
						"yyyy-MM-dd") + "~" + DateUtil.format(termTime.getTetiTermEndDate(), "yyyy-MM-dd") + " 】");
			}
		}*/
		// 获取节次
		LambdaQueryWrapper<CourseSessions> courseSessionsQuery = new LambdaQueryWrapper<>();
		courseSessionsQuery.orderByAsc(CourseSessions::getCoseCode);
		List<CourseSessions> courseSessionsList = courseSessionsService.list(courseSessionsQuery);
		// 封装条件
		WeekCourseTableBySchoolClassReqVo reqVo = new WeekCourseTableBySchoolClassReqVo();
		if (StrUtil.isNotEmpty(scclId)) {
			reqVo.setScclId(Long.parseLong(scclId));
		}
		if (StrUtil.isNotEmpty(syusId)) {
			reqVo.setSyusId(Long.parseLong(syusId));
		}
		if (StrUtil.isNotEmpty(subjId)) {
			reqVo.setSubjId(Long.parseLong(subjId));
		}
		if (StrUtil.isNotEmpty(copsId)) {
			reqVo.setCopsId(Long.parseLong(copsId));
		}
		
		reqVo.setCourBeginAreaTime(DateUtil.parse(courBeginAreaTime + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
		reqVo.setCourEndAreaTime(DateUtil.parse(courEndAreaTime + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
		WeekCourseTableBySchoolClassRspVo rspVo = courseService.getClassCourseTable(courseSessionsList, reqVo);
		rspVo.setTermTime(termTime); // 设置学年学期
		WeekVo weekVo = null;
		if (termTime != null) {
			weekVo = this.calcWeekCask(termTime, reqVo.getCourBeginAreaTime(), reqVo.getCourEndAreaTime());
		}
		rspVo.setWeekVo(weekVo);
		return CommonResult.success(rspVo);
	}
	
	/**
	 * 计算当前周日期的week周次值
	 *
	 * @throws
	 * @author fangjin.tao
	 * @param: termTime
	 * @param: reqVo
	 * @updateTime 2023/2/8 13:58
	 */
	private WeekVo calcWeekCask(TermTime termTime, Date weekBegin, Date weekEnd) {
		Date weekTermTimeBeginDate = CourseUtils.calcWeekBeginDate(termTime);
		Date weekTermTimeEndDate = CourseUtils.calcWeekEndDate(termTime);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(weekTermTimeBeginDate);
		WeekVo weekVo = null;
		for (int week = 1; DateUtil.beginOfDay(calendar.getTime()).getTime() < DateUtil.beginOfDay(weekTermTimeEndDate).getTime(); ) {
			weekVo = null;
			if (calendar.getTime().getTime() == DateUtil.beginOfDay(weekBegin).getTime()) {
				weekVo = new WeekVo();
				weekVo.setWeekNo(week);
				weekVo.setWeekBeginDate(DateUtil.format(calendar.getTime(), "yyyy-MM-dd"));
			}
			calendar.add(Calendar.DAY_OF_MONTH, 6);
			if (weekVo != null && DateUtil.beginOfDay(calendar.getTime()).getTime() == DateUtil.beginOfDay(weekEnd).getTime()) {
				weekVo.setWeekEndDate(DateUtil.format(calendar.getTime(), "yyyy-MM-dd"));
				return weekVo;
			}
			
			calendar.add(Calendar.DAY_OF_MONTH, 1);
			week++;
		}
		return weekVo;
	}
	
	/**
	 * @throws
	 * @author fangjin.tao
	 * @param: coursePlan
	 * @updateTime 2023/2/7 15:17
	 * @return: cn.school.common.api.CommonResult<java.lang.String>
	 */
	@ApiOperation("创建或更新课程")
	@PostMapping("/createOrUpdate")
	public CommonResult<String> createOrUpdate(@RequestBody Course course) {
		this.courseService.saveOrUpdateMyDefined(course);
		return CommonResult.success();
	}
	
	/**
	 * @throws
	 * @author fangjin.tao
	 * @param: coursePlan
	 * @updateTime 2023/2/7 15:17
	 * @return: cn.school.common.api.CommonResult<java.lang.String>
	 */
	@ApiOperation("创建或更新课程")
	@DeleteMapping("/delete/{id}")
	public CommonResult<String> delete(@PathVariable("id") Long courId) {
		this.courseService.deleteCourse(courId);
		return CommonResult.success();
	}
	
}
